﻿using System;
using System.ComponentModel;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;

namespace Caraya.MFG.BusinessPlugIn
{
    [Description("二开应收单插件"), HotUpdate]
    public class Ysd : AbstractDynamicFormPlugIn
    {
        public override void BarItemClick(BarItemClickEventArgs e)
        {
            base.BarItemClick(e);
            if (e.BarItemKey.Equals("ora_jmb_Button"))
            {
                var bill = this.Model.DataObject;
                var fdate = this.View.Model.GetValue("FDate");
                var rate = this.View.BillBusinessInfo.GetField("F_jmb_rate");
                var rate_value = float.Parse(rate.DynamicProperty.GetValue(bill).GetString());
                var factor = this.View.BillBusinessInfo.GetField("F_Price_Factor");
                var factor_value = float.Parse(factor.DynamicProperty.GetValue(bill).GetString());
                var fldMaterial = this.View.BillBusinessInfo.GetField("FMATERIALID");
                var entity = this.View.BillBusinessInfo.GetEntity("FEntityDetail");
                DynamicObjectCollection entityRows = entity.DynamicProperty.GetValue(bill) as DynamicObjectCollection;
                int index = 0;
                foreach (var row in entityRows)
                {
                    bool isFree = bool.Parse(row["IsFree"].ToString());
                    if (!isFree)
                    {
                        DynamicObject tmp = fldMaterial.DynamicProperty.GetValue(row) as DynamicObject;
                        var fldMaterialValue = tmp[0];
                        var sql = "SELECT FPRICE FROM T_SAL_PRICELISTENTRY WHERE (FFORBIDSTATUS='A') AND (FMATERIALID = " + fldMaterialValue.ToString() + ") AND (FEFFECTIVEDATE <= CONVERT(DATETIME, {ts'" + fdate.ToString() + "'})) AND (FEXPRIYDATE >= CONVERT(DATETIME, {ts'" + fdate.ToString() + "'}))";
                        var jmbdj = float.Parse(DBServiceHelper.ExecuteScalar(this.Context, sql, "0"));
                        this.Model.SetValue("FTaxPrice", Math.Round(jmbdj * rate_value * factor_value, 2), index);
                        this.Model.SetValue("F_jmb_Price", jmbdj, index);
                        this.View.InvokeFieldUpdateService("TaxPrice", index + 1);
                    }
                    index++;
                }
                this.View.UpdateView();
            }
        }
    }
}
